package com.books4sale.admin.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONWriter;

import com.books4sale.admin.dto.Book;
import com.books4sale.admin.dto.Profile;
import com.books4sale.admin.dto.tools.Helper;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

public class EditBookInfoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Helper helper = Helper.get();
		String bookName = req.getParameter(helper.BOOK_NAME);
		String bookCollage = req.getParameter(helper.BOOK_COLLAGE);
		String bookSubject = req.getParameter(helper.BOOK_SUBJECT);
		String bookPrice = req.getParameter(helper.BOOK_PRICE);
		Long bookId = Long.parseLong(req.getParameter(helper.BOOK_ID));
//		String bookId = req.getParameter(helper.BOOK_ID);
		String rowIndex = req.getParameter(helper.ROW_INDEX);

		User currentUser = helper.getCurrentUser();
		Date currentDate = helper.getCurrentDate();

		Book book = new Book(currentUser, currentDate, bookName, bookCollage,
				bookSubject, bookPrice);
		KeyFactory.Builder builder = new KeyFactory.Builder(Profile.class
				.getSimpleName(), helper.getCurrentUser().getEmail());
//		Long id = Long.parseLong(bookId.substring(bookId.lastIndexOf("(")+1, bookId.lastIndexOf(")")));
		builder.addChild(Book.class.getSimpleName(), bookId);
		Key beingEditedBookKey = builder.getKey();
		book.setId(beingEditedBookKey);

		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

		book = helper.editBook(book);
		if (null != book) {
			PrintWriter writer = resp.getWriter();
			JSONWriter jSONWriter = new JSONWriter(writer);
			try {
				jSONWriter.object().key("bookId").value(book.getId().getId()+ "").key(
						"rowIndex").value(rowIndex).key("bookName").value(
						book.getBookName()).key("bookCollage").value(
						book.getBookCollage()).key("bookSubject").value(
						book.getBookSubject()).key("bookPrice").value(
						book.getBookPrice()).endObject();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
